/*
 * $Id: SyncToHeadAction.java 67 2002-11-03 18:37:46Z bpruessmann $
 * 
 * Copyright (c) 2001,2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.ui.action;

import java.lang.reflect.InvocationTargetException;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.internal.P4TeamProvider;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

/**
  * @version $Revision: 67 $
  * @author  <a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class SyncToHeadAction extends PerforceAction
{
	// ------------------------------------------------------------------------------ Public Methods
	
	/** @see IActionDelegate#run(IAction) */
	public void run(IAction action)
	{
		run(new WorkspaceModifyOperation()
		{
			public void execute(IProgressMonitor monitor) 
				throws InterruptedException, InvocationTargetException 
			{
				IResource[] resources = getSelectedResources();
				try
				{
					P4TeamProvider provider = 
						P4TeamProvider.getProvider(resources[0]);						
					provider.get(resources, IResource.DEPTH_INFINITE, monitor);
				}
				catch (TeamException e)
				{
					throw new InvocationTargetException(e);
				}					
			}				
		}, PROGRESS_DIALOG);
	}
	
	// --------------------------------------------------------------------------- Protected Methods
	
	/** @see TeamAction#isEnabled() */
	protected boolean isEnabled() 
		throws PerforceException
	{
		IResource[] resources = getSelectedResources();
		if (resources.length == 0)
		{
			return false;
		}
			
		for (int i = 0; i < resources.length; i++) 
		{
			RepositoryProvider tempProvider = 
				RepositoryProvider.getProvider(resources[i].getProject());
			if (tempProvider == null || 
			    !tempProvider.getID().equals(PerforceCorePlugin.getTypeId()))
			{
				return false;
			}
				
			P4TeamProvider provider = (P4TeamProvider) tempProvider;
			if (provider.isCheckedOut(resources[i]))
			{
				return false;
			}
				
			if (!provider.hasRemote(resources[i])) 
			{
				return false;	
			}
		}
		return true;
	}
}
